<template>
  <div>
    <div :style="{ height: '20px' }"></div>
    <div :style="{ background: '#ffffff' }">
      <a-table :columns="columns" :data-source="dataSource" :pagination="false" size="small" bordered>
        <template slot="name" slot-scope="text">
          <a>{{ text }}</a>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import Factor from './Factor';
import FactorValue from './FactorValue';

const h = new Vue().$createElement;

//
const factorIsCoinsurance = new Factor({
  name: 'isCoinsurance',
  title: '是否共保',
});
factorIsCoinsurance.addValue({ name: 'yes', title: '是' });
factorIsCoinsurance.addValue({ name: 'no', title: '否' });

//
const factorRiskRank = new Factor({ name: 'riskRank', title: '风险等级' });
factorRiskRank.addValue({ name: 'rankA', title: 'A 级' });
factorRiskRank.addValue({ name: 'rankB', title: 'B 级' });
factorRiskRank.addValue({ name: 'rankC', title: 'C 级' });

//
const factorPolicyLimit = new Factor({ name: 'policyLimit', title: '保额区间' });
factorPolicyLimit.addValue({ name: 'lessThan500', title: '少于 500 万' });
factorPolicyLimit.addValue({ name: 'greaterThan500', title: '500 万以上' });

//
const factorPolicyholderGender = new Factor({
  name: 'policyholderGender',
  title: '投保人性别',
});
factorPolicyholderGender.addValue({ name: 'male', title: '男' });
factorPolicyholderGender.addValue({ name: 'female', title: '女' });

//
const factorPolicyTag = new Factor({
  name: 'policyTag',
  title: '保单管理标签',
});
factorPolicyTag.addValue({ name: 'personal', title: '个人客服' });
factorPolicyTag.addValue({ name: 'corporate', title: '企业客服' });
factorPolicyTag.addValue({ name: 'priority', title: '重要客服' });

//
const factorAgeRange = new Factor({
  name: 'ageRange',
  title: '年龄区间',
});
factorAgeRange.addValue({ name: '10-20', title: '10-20' });
factorAgeRange.addValue({ name: '20-30', title: '20-30' });
factorAgeRange.addValue({ name: '30-40', title: '30-40' });
factorAgeRange.addValue({ name: '40-50', title: '40-50' });
factorAgeRange.addValue({ name: '50-60', title: '50-60' });
factorAgeRange.addValue({ name: '60-70', title: '60-70' });
factorAgeRange.addValue({ name: '70-80', title: '70-80' });

const rowFactors = [factorPolicyholderGender, factorPolicyTag, factorAgeRange];
const columnFactors = [factorPolicyLimit, factorIsCoinsurance, factorRiskRank];

const getColSpan = (fieldName, rowIndex) => {
  // if (rowIndex === 4) {
  //   if (fieldName === 'name') {
  //     return 5
  //   } else {
  //     return 0
  //   }
  // }
  return 1;
};

const getRowSpan = (fieldName, rowIndex) => {
  // if (fieldName === 'tel') {
  // if (rowIndex === 0) {
  //   retW
  // } else if (rowIndex === 1 || rowIndex === 2) {
  //   return 0
  // }
  // }

  // console.log('in get row span:', fieldName, rowIndex)

  // 投保人性别
  if (fieldName === 'policyholderGender') {
    return getPolicyholderGenderRowSpan(rowIndex);
  }

  // 保单管理标签
  if (fieldName === 'policyTag') {
    return getPolicyTagRowSpan(rowIndex);
  }

  return 1;
};

const getPolicyholderGenderRowSpan = (rowIndex) => {
  // const policyholderGenderFlatValueCount = [21, 21]
  // const rowIndexPoint = [0, 21, 42]
  // // if (rowIndex === ) {

  // // }

  // if (rowIndex === 0 || rowIndex === 21) {
  //   return 21
  // }
  // return 0

  const breakRowIndex = [0, 21, 42];

  const breakPoints = [
    { index: 0, length: 21 },
    { index: 21, length: 21 },
  ];

  const breakPointIndex = breakRowIndex.findIndex((indexItem) => indexItem === rowIndex);

  if (breakPointIndex >= 0) {
    return breakRowIndex[breakPointIndex + 1] - breakRowIndex[breakPointIndex];
  }

  return 0;
};

const getPolicyTagRowSpan = (rowIndex) => {
  const breakRowIndex = [0, 7, 14, 21, 28, 35, 42, 49];

  const breakPointIndex = breakRowIndex.findIndex((indexItem) => indexItem === rowIndex);

  if (breakPointIndex >= 0) {
    return breakRowIndex[breakPointIndex + 1] - breakRowIndex[breakPointIndex];
  }

  return 0;
};

const cellRender = ({ name, value, values, rowIndex } = {}) => {
  // console.log('[function] cellRender', name)
  const colSpan = getColSpan(name, rowIndex);
  const rowSpan = getRowSpan(name, rowIndex);
  const cellData = {
    children: <span>{value}</span>,
    attrs: {
      colSpan,
      rowSpan,
    },
  };

  return cellData;
};

const buildColGroup = (colFactors, factorIndex = 0, valuePaths = []) => {
  // 如果列因子为空，直接返回
  if (colFactors.length <= 0) {
    return [];
  }

  const factor = colFactors[factorIndex];
  return factor.values.map((value) => buildColData(colFactors, value, factorIndex, valuePaths));
};

const buildColData = (colFactors, factorValue, factorIndex, valuePaths) => {
  const newPaths = [...valuePaths, factorValue.name];
  let colData = {
    title: factorValue.title,
    name: factorValue.name,
    paths: newPaths,
    customRender: (value, values, rowIndex) => cellRender({ name: factorValue.name, value, values, rowIndex }),
  };

  if (factorIndex < colFactors.length - 1) {
    // is not last factor, has children
    colData.children = buildColGroup(colFactors, factorIndex + 1, newPaths);
  } else {
    // is last factor
    colData.dataIndex = newPaths.join(':');
  }
  return colData;
};

const buildRowFactorCol = (rowFactors) => {
  return rowFactors.map((rowFactor) => {
    return {
      title: rowFactor.title,
      dataIndex: rowFactor.name,
      paths: [rowFactor.value],
      customRender: (value, values, rowIndex) => cellRender({ name: rowFactor.name, value, values, rowIndex }),
    };
  });
};

const buildColumns = () => {
  const rowFactorColumns = buildRowFactorCol(rowFactors);
  const colFactorColumns = buildColGroup(columnFactors);
  return [...rowFactorColumns, ...colFactorColumns];
};

let keyIndex = 1;
const genKey = () => {
  return `key-${keyIndex++}`;
};

const buildRowFactorDatas = (allFactors, factorIndex = 0, rowData = {}, result = []) => {
  const factor = allFactors[factorIndex];

  factor.values.forEach((value, valueIndex) => {
    const newRowData = { ...rowData, [factor.name]: value.title };
    if (factorIndex === allFactors.length - 1) {
      result.push({ ...newRowData, key: genKey() });
    } else {
      // console.log('now do loop:', newRowData)
      buildRowFactorDatas(allFactors, factorIndex + 1, newRowData, result);
    }
  });

  return result;
};

// const doIt = () => {
//   // let rowData = {}
//   // handleValue(rowFactors, 0, rowData)

//   let result = handleValue(rowFactors)

//   console.log('>> result is:', result)
// }

const buildDataSource = () => {
  const dataSource = buildRowFactorDatas(rowFactors);
  console.log('data source :', dataSource);
  return dataSource;

  // let dataSource = []

  // rowFactors.forEach((factor) => {})

  // factorPolicyholderGender.values.forEach((value) => {
  //   const key = genKey()
  //   const fieldName = factorPolicyholderGender.name
  //   const cellValue = value.title
  //   dataSource.push({
  //     key,
  //     [fieldName]: cellValue,
  //   })
  // })

  // console.log('data source is:', dataSource)

  // dataSource = [
  //   {
  //     key: genKey(),
  //     policyholderGender: '男',
  //     policyTag: '个人客服',
  //     ageRange: '10-20',
  //   },
  //   {
  //     key: genKey(),
  //     policyholderGender: '男',
  //     policyTag: '个人客服',
  //     ageRange: '20-30',
  //   },
  //   {
  //     key: genKey(),
  //     policyholderGender: '男',
  //     policyTag: '企业客服',
  //     ageRange: '20-30',
  //   },
  //   {
  //     key: genKey(),
  //     policyholderGender: '女',
  //     policyTag: '个人客服',
  //     ageRange: '20-30',
  //   },
  //   {
  //     key: genKey(),
  //     policyholderGender: '女',
  //     policyTag: '企业客服',
  //     ageRange: '50-60',
  //   },
  //   {
  //     key: genKey(),
  //     policyholderGender: '女',
  //     policyTag: '企业客服',
  //     ageRange: '70-80',
  //   },
  // ]

  // return dataSource
};

const output = buildColGroup(columnFactors);
// console.log('>>>output is:', output)

// const data = [
//   {
//     key: '1',
//     name: 'John Brown',
//     age: 32,
//     tel: '0571-22098909',
//     phone: 18889898989,
//     tel2: '0571-22098909',
//     phone2: 18889898989,
//     address: 'New York No. 1 Lake Park',
//   },
//   {
//     key: '100',
//   },
//   // {
//   //   key: '2',
//   //   name: 'Jim Green',
//   //   tel: '0571-22098333',
//   //   phone: 18889898888,
//   //   tel2: '0571-22098909',
//   //   phone2: 18889898989,
//   //   age: 42,
//   //   address: 'London No. 1 Lake Park',
//   // },
//   // {
//   //   key: '3',
//   //   name: 'Joe Black',
//   //   age: 32,
//   //   tel: '0575-22098909',
//   //   phone: 18900010002,
//   //   tel2: '0571-22098909',
//   //   phone2: 18889898989,
//   //   address: 'Sidney No. 1 Lake Park',
//   // },
//   // {
//   //   key: '4',
//   //   name: 'Jim Red',
//   //   age: 18,
//   //   tel: '0575-22098909',
//   //   phone: 18900010003,
//   //   tel2: '0571-22098909',
//   //   phone2: 18889898989,
//   //   address: 'London No. 2 Lake Park',
//   // },
//   // {
//   //   key: '5',
//   //   name: 'Jake White',
//   //   age: 18,
//   //   tel: '0575-22098909',
//   //   phone: 18900010004,
//   //   tel2: '0571-22098909',
//   //   phone2: 18889898989,
//   //   address: 'Dublin No. 2 Lake Park',
//   // },
// ]

const myColumns = [
  {
    title: 'Name',
    dataIndex: 'name',
    customRender: (value, values, rowIndex) => cellRender({ name: 'name', value, values, rowIndex }),
    // customRender: () => {
    //   return {
    //     children: 123,
    //     atrrs: {
    //       colSpan: 1,
    //     },
    //   }
    // },
  },
  {
    title: 'Age',
    dataIndex: 'age',
    customRender: (value, values, rowIndex) => cellRender({ name: 'age', value, values, rowIndex }),
  },
  {
    title: 'Home phone',
    children: [
      {
        title: 'A',
        children: [
          {
            title: 'a-1',
            dataIndex: 'tel',
            customRender: (value, values, rowIndex) => cellRender({ name: 'tel', value, values, rowIndex }),
          },
          {
            title: 'a-2',
            dataIndex: 'phone',
            customRender: (value, values, rowIndex) => cellRender({ name: 'tel', value, values, rowIndex }),
          },
        ],
      },
      {
        title: 'B',
        dataIndex: 'phone2',
        customRender: (value, values, rowIndex) => cellRender({ name: 'phone2', value, values, rowIndex }),
      },
    ],
    // colSpan: 2,
    // dataIndex: 'tel',
    // customRender: (value, values, rowIndex) =>
    //   cellRender({ name: 'tel', value, values, rowIndex }),
    // customRender: (value, row, index) => {
    //   const obj = {
    //     children: value,
    //     attrs: {},
    //   }
    //   if (index === 2) {
    //     obj.attrs.rowSpan = 2
    //   }
    //   // These two are merged into above cell
    //   if (index === 3) {
    //     obj.attrs.rowSpan = 0
    //   }
    //   if (index === 4) {
    //     obj.attrs.colSpan = 0
    //   }
    //   return obj
    // },
  },
  // {
  //   title: 'Phone',
  //   colSpan: 0,
  //   dataIndex: 'phone',
  //   customRender: (value, values, rowIndex) =>
  //     cellRender({ name: 'phone', value, values, rowIndex }),
  //   // customRender: renderContent,
  // },
  {
    title: 'Address',
    dataIndex: 'address',
    customRender: (value, values, rowIndex) => cellRender({ name: 'address', value, values, rowIndex }),
    // customRender: renderContent,
  },
];

export default {
  name: 'tableTest1',
  components: {},
  data() {
    const dataSource = buildDataSource();
    const columns = buildColumns();

    // console.log('columns:', columns)

    return {
      dataSource,
      columns,
    };
  },
  computed: {
    // columns(h) {
    //   return myColumns
    // },
  },
};
</script>

<style></style>
